<template>
	<view class="adup-wxbz page-bg">
		<view class="fm-title">
			<view class="title"><label class="line-icon" :style="{'background': '#00c3c3'}"></label>维修报账</view>
			<u-button :loading="sb.load" type="success" @click="submitFm">
				<u-icon v-if="!sb.load" name="edit-pen-fill" color="#fff"
					:custom-style="{'margin-right': '10rpx'}"></u-icon>
				提交修改
			</u-button>
		</view>

		<u-form :model="fm" ref="bzfm" v-if="fm">
			<view class="my-fm">
				<view class="f-item no-box">
					<u-form-item>
						<view class="i-row">
							<view class="r-title">公里数</view>
							<view class="r-con">
								<u-input v-model="fm.currKm" :type="'digit'" :maxlength="8" :input-align="'right'"
									:clearable="false" :custom-style="{'color': '#00C3CE'}"
									placeholder="请输入车辆当前公里数" /><label class="i-r-text">公里</label>
							</view>
						</view>
					</u-form-item>

					<u-form-item>
						<view class="i-row">
							<view class="r-title">维修站</view>
							<view class="r-con">
								<MySelect :title="'维修站'" :name="'wxStation'" :list="wxStationList"
									:defval="fm.wxStation" @seledItem="mySeledMd"></MySelect>
							</view>
						</view>
					</u-form-item>

					<u-form-item>
						<view class="i-row">
							<view class="r-title">支付方式</view>
							<view class="r-con">
								<MySelect :title="'支付方式'" :name="'wxPayWay'" :list="payWayList" :defval="fm.wxPayWay"
									@seledItem="mySeledMd"></MySelect>
							</view>
						</view>
					</u-form-item>

					<u-form-item>
						<view class="i-row">
							<view class="r-title">维修日期</view>
							<view class="r-con">
								<MyDateTime :name="'wxDate'" :showType="1" :datePlaceholder="'维修日期'"
									:dateTime="fm.wxDate" @myClick="setDateTime"></MyDateTime>
							</view>
						</view>
					</u-form-item>

					<u-form-item>
						<view class="i-row">
							<view class="r-title">维修金额</view>
							<view class="r-con">
								<u-input v-model="fm.reimMoney" :type="'digit'" :maxlength="6" :input-align="'right'"
									:clearable="false" :custom-style="{'color': '#00C3CE'}"
									:placeholder="'请输入加油金额'" /><label class="i-r-text">元</label>
							</view>
						</view>
					</u-form-item>
					<u-form-item>
						<view class="i-row">
							<view class="r-title">是否保养</view>
							<view class="r-con">
								<MySelect :title="'是否保养'" :name="'isMaintenance'" :list="isMaintenanceList" :defval="fm.isMaintenance"
									@seledItem="mySeledMd"></MySelect>
							</view>
						</view>
					</u-form-item>
					<u-form-item>
						<view class="i-row-textarea">
							<view class="r-title">备注</view>
							<view class="r-con">
								<u-input v-model="fm.wxRemark" :type="'textarea'" :custom-style="{'color': '#00C3CE'}"
									:placeholderStyle="'color: #f000000;'" :clearable="false" :auto-height="true"
									:height="150" :maxlength="200" :placeholder="'请填写维修报账备注，最多输入200个字（选填）'" />
							</view>
						</view>
					</u-form-item>

					<u-form-item :border-bottom="false">
						<view class="i-row-textarea">
							<view class="r-title">报账凭证<label class="r-title-tip">（最多上传6张图片）</label></view>
							<view class="r-con">
								<u-upload ref="bzUf" width="200" height="200" max-count="6" :file-list="fm.uflist"
									:action="ufAction" :header="ufHeader" :name="'files'"
									:form-data="{ftype: fm.bzType.key+'_IMG', orderNum: fm.plateNum, uid: fm.uid}"
									:max-size="1024*1024*30"></u-upload>
							</view>
						</view>
					</u-form-item>
				</view>
			</view>
		</u-form>

		<u-toast ref="qtoast" />
	</view>
</template>

<script>
	import MySelect from '@/components/my-select/my-select.vue';
	import MyDateTime from '@/components/my-date-time/my-date-time.vue';

	export default {
		components: {
			MySelect,
			MyDateTime
		},
		data() {
			return {
				plateNum: '',
				// 维修详情输入框样式
				inpBtnStyl: {
					'color': '#00C3CE',
					'padding-right': '30rpx'
				},

				// 文件上传地址
				ufAction: this.C.upfileUrl,
				// 文件上传请求头信息
				ufHeader: {
					'token': uni.getStorageSync(this.C.uuid)
				},
				// 旧文件数据
				flist: [],

				// 表单对象
				fm: null,
				// 提交按钮
				sb: {
					load: false
				},

				// 维修站列表
				wxStationList: [],
				// 维修支付方式列表
				payWayList: [{
						val: 'ACCOUNTING',
						text: '记账'
					},
					{
						val: 'CASH',
						text: '现金'
					},
				],
				isMaintenanceList: [{
						val: '0',
						text: '否'
					},
					{
						val: '1',
						text: '是'
					},
				],
			}
		},
		onLoad(e) {
			console.log('传入的参数', e);

			this.getUnRouteBzBaseData(e.id);


		},
		computed: {
			// 维修项总金额
			wxTotalMoney: function() {
				let total = 0;
				if (this.fm && this.fm.wxItems) {
					this.fm.wxItems.forEach(it => {
						total += Number(it.money);
					});
				}
				return total;
			}
		},
		methods: {
			// 弹框列表选择
			mySeledMd(e) {
				this.fm[e.name] = e.obj;
			},
			// 选择日期时间
			setDateTime(e) {
				this.fm[e.name] = e.obj;
			},
			/**
			 * 添加/删除-维修项
			 * @param {Object} type 操作类型 1-添加 0-删除
			 * @param {Object} index 下标
			 */
			adupWxItems(type, index) {
				let that = this,
					U = that.U,
					pklist = that.fm.wxItems;
				console.log('传入的值', type, index);
				if (type == 0) {
					U.qconfim('确定删除吗？', function(e) {
						if (e.confirm) pklist.splice(index, 1);
					});
				} else {
					let arr = [];
					pklist.forEach((it, i) => {
						arr.push(it);
						if (i == index) arr.push({
							id: 'wx_' + pklist.length + 1,
							label: '',
							money: ''
						});
					});
					that.fm.wxItems = arr;

					console.log('新增的结果', that.fm.wxItems);
				}
			},

			// 获取-非团上开支报账基本数据
			async getUnRouteBzBaseData(e) {
				let that = this
				let res2 = await that.$u.api.findComboCusList({
					cusTypeMark: 'REPAIR',
					page: {
						pageNum: 1,
						pageSize: 999,
					}
				});
				if (res2.code == 1) {

					// 设置-维修站列表
					that.wxStationList = [];
					res2.data.forEach(it => {
						that.wxStationList.push({
							val: it.id,
							text: it.cusCompanySimpleName
						});
					});
					that.getBzDetail(e);

				}

			},
			// 获取-报账详情
			getBzDetail(id) {
				const that = this;

				that.$u.api.getBzDetail({
					id: id
				}).then(res => {
					if (res.code == 1) {
						let o = res.data;

						// 根据报账类型初始化对应数据
						let p = {};
						// 修改id
						p.id = o.id;
						// 报账车辆车牌
						// 报账车辆车牌
						that.plateNum = o.plateNum;
						p.plateNum = o.plateNum;
						// 报账类型
						p.bzType = 'WXJZ';
						// 车辆当前公里数
						p.currKm = o.currentKilo;

						let payWayList = [{
								val: 'ACCOUNTING',
								text: '记账'
							},
							{
								val: 'CASH',
								text: '现金'
							},
						]
						let isMaintenanceList = [{
								val: '0',
								text: '否'
							},
							{
								val: '1',
								text: '是'
							},
						]
						// 支付方式
						if (o.payWay) p.wxPayWay = {

							text: o.payWay
						};
						for (let i = 0; i < payWayList.length; i++) {
							if (o.payWay == payWayList[i].text) {
								p.wxPayWay.val = payWayList[i].val
							}
						}

						// 是否保养
						if (o.isMaintenance) {
							p.isMaintenance = {

								val: o.val
							};
						} else {
							o.isMaintenance = '0'
							p.isMaintenance = {

								val: '0'
							};
						}

						for (let i = 0; i < isMaintenanceList.length; i++) {
							if (o.isMaintenance == isMaintenanceList[i].val) {
								p.isMaintenance.text = isMaintenanceList[i].text
							}
						}

						// 维修站
						if (o.stationName) p.wxStation = {

							text: o.stationName
						};
						for (let i = 0; i < that.wxStationList.length; i++) {
							if (o.stationName == that.wxStationList[i].text) {
								p.wxStation.val = that.wxStationList[i].val
							}
						}

						// 加油日期
						p.wxDate = {
							date: that.datatime(o.payTime),
							time: ''
						};
						// 金额
						p.reimMoney = o.reimMoney;
						// 备注
						p.wxRemark = o.remark;
						// 图片id
						p.fids = [];
						// 默认图片数组
						let flist = [];
						if (o.reimVoucherUrl) {
							let fs = o.reimVoucherUrl.split(',');
							fs.forEach(it => {
								flist.push({
									url: 'https://cba360.com' + it
								});
							});
						}
						that.flist = flist; // 保存起来
						p.uflist = flist;

						that.fm = p;
						console.log('赋值', that.fm);
					}
				});
			},
			// 表单验证
			valFm() {
				const that = this,
					U = that.U,
					FV = that.FV;
				let fg = true,
					ps = U.scopy(that.fm),
					p = {};

				p.jzType = ps.bzType.key;
				p.id = ps.id;
				p.moneyTypeId = 9;

				if (fg) {
					let plateNum = ps.plateNum;
					if (!plateNum) {
						fg = U.qinfo('请选择维修辆车');
					} else if (plateNum.length > 8) {
						fg = U.qinfo('车牌号格式错误');
					} else {
						p.plateNum = plateNum;
					}
				}

				if (fg) {
					let currKm = ps.currKm;
					if (!currKm || currKm < 1) {
						fg = U.qinfo('[维修车辆当前公里数]不能为空');
					} else {
						p.currentKilo = currKm;
					}
				}

				if (fg) {
					let wxStation = ps.wxStation.val;
					if (!wxStation) {
						fg = U.qinfo('[维修站]不能为空');
					} else {
						p.stationId = wxStation;
					}
				}

				if (fg) {
					let wxPayWay = ps.wxPayWay.val;
					if (!wxPayWay) {
						fg = U.qinfo('[支付方式]不能为空');
					} else {
						p.payWay = wxPayWay;
					}
				}
				if (fg) {
					let isMaintenance = ps.isMaintenance.val;
					if (!isMaintenance) {
						fg = U.qinfo('[是否保养]不能为空');
					} else {
						p.isMaintenance = isMaintenance;
					}
				}

				if (fg) {
					let wxDate = ps.wxDate.date;
					if (!wxDate) {
						//fg = U.qinfo('[维修日期]不能为空');
					} else if (U.str2date(wxDate + ' 00:00:00').getTime() > new Date().getTime()) {
						fg = U.qinfo('[维修日期]不能大于当前时间');
					} else {
						p.payTime = wxDate;
					}
				}

				if (fg) {
					let reimMoney = ps.reimMoney;
					if (!reimMoney || reimMoney == 0) {
						fg = U.qinfo('[金额]不能为空或0');
					} else if (!FV.isFloat(reimMoney)) {
						fg = U.qinfo('[金额]格式错误');
					} else {
						p.reimMoney = reimMoney;
					}
				}

				if (fg) {
					let wxRemark = ps.wxRemark;
					if (wxRemark && wxRemark.length > 200) {
						fg = U.qinfo('[备注]最多填写200个字');
					} else {
						p.remark = wxRemark;
					}
				}

				if (fg) {
					let uflist = that.$refs.bzUf.lists;
					if (uflist.length == 0) {
						fg = U.qinfo('至少需要上传一张维修清单图片');
					} else {
						let fids = [];
						uflist.forEach(it => {
							if (it.url && it.url.indexOf('_img') != -1) { // 本地图片
								let is = that.flist.find(fit => it.url.indexOf(fit.url) != -1);
								let url = is.url.split('.com')[1]
								console.log(url, 'url')
								fids.push(url);
							} else { // 新传图片
								if (it.response && it.response.data) fids.push(it.response.data.file.url);
							}
						});
						if (fids.length == 0) {
							fg = U.qinfo('上传图片' + uflist.length + '张，成功' + fids.length + '张');
						} else {
							p.reimVoucherUrl = fids.join(',');
						}
					}
				}

				return fg ? {
					staffReimInfo: [p]
				} : fg;
			},
			// 提交表单
			submitFm() {
				let that = this,
					ps = that.valFm(),
					U = that.U,
					sb = that.sb;
				if (ps != false) {
					ps.plateNum = that.plateNum
					console.log('提交参数', ps);
					sb.load = true;
					that.$u.api.adupAllUnRouteBz(ps).then((res) => {
						if (res.code != 1) {
							sb.load = false;
						} else {
							U.qtoast(that, {
								title: res.msg,
								type: 'success',
								duration: 1000,
								callback: function() {
									sb.load = false;

									// 刷新父级列表（刷新未报销的列表）
									uni.$emit('refJzList', 0);
									// 返回上一页
									uni.navigateBack({
										delta: 1
									});
								}
							});
						}
					}).catch(err => {
						sb.load = false;
					});
				}
			},
			datatime(e) {
				let originalDateTimeString = e;
				let date = new Date(originalDateTimeString);

				let year = date.getFullYear();
				let month = String(date.getMonth() + 1).padStart(2, '0');
				let day = String(date.getDate()).padStart(2, '0');
				let hours = String(date.getHours()).padStart(2, '0');
				let minutes = String(date.getMinutes()).padStart(2, '0');
				let seconds = String(date.getSeconds()).padStart(2, '0');

				let formattedDateTimeString = `${year}-${month}-${day}`;
				return formattedDateTimeString
			},
		}
	}
</script>

<style lang="scss">
	.adup-wxbz {
		padding-top: 80rpx;
		padding-bottom: 10rpx;

		.f-item {
			margin: 10rpx !important;
		}
	}
</style>